package controller.transform;

import javax.media.j3d.Transform3D;

import component.AbstractComponent;
import component.Status;
import component.group.ComponentGroup;
import component.traverse.Traverse;

public abstract class RotateMode extends TransformMode {

	protected ComponentGroup border;
	protected ComponentGroup grabbedSelection = null;
	protected AbstractComponent grabbedComponent = null;
	protected Transform3D transformHistory = new Transform3D();

	public RotateMode(Gui gui, Scene scene) {
		super(gui, scene);
	}

	protected void setDefaultHelp() {
		gui.setStatusText("Left click and grab a component to rotate. Right click to deselect.");
	}
	protected void selectComponent(AbstractComponent component) {
		unselectComponent();
		if (component != null) {
			grabbedComponent = component;
			grabbedComponent.setStatus(Status.HIGHLIGHTED, true);
			makeSelection();
			this.setLegalGroupState();
		}
	}
	
	protected void unselectComponent() {
		if (grabbedComponent != null) {
			grabbedComponent.setStatus(Status.NORMAL);
			grabbedComponent = null;
		}
		if (grabbedSelection != null) {
			grabbedSelection.setStatus(Status.NORMAL);
			grabbedSelection.clear();
			grabbedSelection = null;
		}
	}
	
	protected void setLegalGroupState() {
		grabbedSelection.setStatusFlag(Status.SELECTED, true);
		grabbedSelection.setStatusFlag(Status.ILLEGAL, false);
	}
	
	protected void setIllegalGroupState() {
		grabbedSelection.setStatusFlag(Status.SELECTED, false);
		grabbedSelection.setStatusFlag(Status.ILLEGAL, true);		
	}
	
	
	private void makeSelection() {
		grabbedSelection = new ComponentGroup();
		Traverse traverse = new Traverse();
		traverse.setBorder(border);
		traverse.addListener(grabbedSelection);
		traverse.traverse(grabbedComponent, ComponentGroup.SELECT);
		if (grabbedSelection.containsLockedComponents()) {
			gui.setStatusText("Selection contains locked components.");
		}
	}
	
	protected void undo() {
		transformHistory.invert();
		if (grabbedSelection != null)
			this.grabbedSelection.applyTransform(transformHistory);
		transformHistory.setIdentity();
	}
}
